<template>
	<page-wrapper :show-tab-bar="false" navTitle="预算" navBackgroundColor="#FFD84D">
		<view class="budget-container">
			<!-- 自定义导航栏 -->
			<!-- <CustomNavbar title="预算" backgroundColor="#FFD84D"></CustomNavbar> -->

			<!-- 月份选择器 - 始终显示 -->
			<view class="month-selector">
				<view class="month-selector-left" @click="showDatePicker">
					<text>{{ currentYear }}年{{ currentMonth }}月</text>
					<uni-icons type="bottom" size="14" :color="textColor"></uni-icons>
				</view>
				<view class="month-selector-right">
					<view v-if="hasBudgetData" class="edit-btn" @click="navigateToEditBudget">
						<text>编辑</text>
					</view>
					<view v-else class="placeholder-btn"></view>
				</view>
			</view>
			
			<!-- 加载状态 -->
			<view class="loading-container" v-if="isLoading">
				<uni-load-more status="loading" :content-text="{ contentdown: '加载中...' }"></uni-load-more>
			</view>
			
			<!-- 有预算数据时显示的内容 -->
			<block v-else-if="hasBudgetData">
				<!-- 预算概览 -->
				<view class="budget-overview">
					<!-- 左侧环形图 -->
					<view class="chart-container">
						<view class="chart-circle">
							<view class="progress-ring" :style="{ background: getProgressGradient() }"></view>
							<view class="inner-circle">
								<text class="remaining-amount">{{ getUsedPercentage() }}%</text>
								<text class="remaining-text">已使用</text>
							</view>
						</view>
					</view>
					
					<!-- 右侧预算信息 -->
					<view class="budget-info">
						<view class="budget-row">
							<text class="budget-label">本月预算</text>
							<text class="budget-value">{{ totalBudget.toFixed(2) }}</text>
						</view>
						<view class="budget-row">
							<text class="budget-label">本月支出</text>
							<text class="budget-value expense-value">{{ totalExpense.toFixed(2) }}</text>
						</view>
						<view class="budget-row">
							<text class="budget-label">剩余预算</text>
							<text class="budget-value">{{ remainingBudget.toFixed(2) }}</text>
						</view>
						<!-- 剩余每日预算 -->
						<view class="budget-row daily-budget">
							<text class="budget-label">每日预算</text>
							<text class="budget-value">{{ dailyBudget.toFixed(2) }}/天</text>
						</view>
					</view>
				</view>
				
				<!-- 预算分类列表 -->
				<scroll-view scroll-y class="budget-categories">
					<view class="category-item" v-for="(item, index) in budgetCategories" :key="index" @click="editCategory(item)">
						<view class="category-left">
							<view class="category-icon" :style="{ backgroundColor: item.color + '40' }">
								<image :src="item.icon" class="category-icon-image" v-if="item.icon"></image>
								<uni-icons :type="item.iconType || 'wallet'" size="24" :color="item.color" v-else></uni-icons>
							</view>
							<view class="category-info">
								<text class="category-name">{{ item.name }}</text>
								<view class="category-progress">
									<progress :percent="calculateCategoryProgress(item)" :stroke-width="3" 
										:activeColor="getCategoryProgressColor(item)" backgroundColor="#E0E0E0" />
									<view class="progress-info">
										<text>已用 {{ item.spent.toFixed(2) }}</text>
										<text>总额 {{ item.amount.toFixed(2) }}</text>
									</view>
								</view>
							</view>
						</view>
						<view class="category-right">
							<text class="remaining-budget" :class="{ 'over-budget': item.spent > item.amount }">
								{{ (item.amount - item.spent).toFixed(2) }}
							</text>
						</view>
					</view>
					
					<!-- 无分类数据提示 -->
					<view class="no-data" v-if="budgetCategories.length === 0">
						<text>暂无预算分类</text>
					</view>
				</scroll-view>
			</block>
			
			<!-- 无预算数据时显示的内容 -->
			<view class="empty-budget" v-else>
				<image src="/static/images/empty-budget.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">您还没有设置本月预算</text>
			</view>
			
			<!-- 添加分类按钮 -->
			<view class="add-category-btn" @click="navigateToAddCategory">
				<text>{{ hasBudgetData ? '添加分类预算' : '创建预算' }}</text>
			</view>
			
			<!-- 月份选择器弹窗 -->
			<uni-popup ref="datePopup" type="bottom">
				<view class="date-picker-popup">
					<view class="picker-header">
						<text @click="cancelDatePicker">取消</text>
						<text @click="confirmDatePicker">确定</text>
					</view>
					<picker-view class="picker-view" :value="[currentYear - startYear, currentMonth - 1]" @change="onDatePickerChange">
						<picker-view-column>
							<view class="picker-item" v-for="(year, index) in yearArray" :key="index">{{year}}年</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="(month, index) in monthArray" :key="index">{{month}}月</view>
						</picker-view-column>
					</picker-view>
				</view>
			</uni-popup>
		</view>
	</page-wrapper>
</template>

<script>
import { themeMixin } from '@/utils/theme.js';
import { getBudgetByYearMonth } from '@/api/budget.js';
import { getBudgetCategoryList } from '@/api/budget-category.js';

export default {
	mixins: [themeMixin],
	data() {
		const currentYear = new Date().getFullYear();
		const startYear = currentYear - 5;
		const endYear = currentYear + 5;
		
		return {
			// 是否有预算数据
			hasBudgetData: false, // 默认为false，通过API判断
			isLoading: false,     // 加载状态
			
			// 日期选择器相关
			currentYear: currentYear,
			currentMonth: new Date().getMonth() + 1,
			tempYear: currentYear,
			tempMonth: new Date().getMonth() + 1,
			startYear: startYear,
			yearArray: Array.from({length: endYear - startYear + 1}, (_, i) => startYear + i),
			monthArray: Array.from({length: 12}, (_, i) => i + 1),
			
			// 预算数据
			budgetId: null,      // 预算ID
			totalBudget: 0.00,   // 本月总预算
			totalExpense: 0.00,  // 本月总支出
			remainingBudget: 0.00, // 剩余预算
			dailyBudget: 0.00,   // 每日剩余预算
			
			// 预算分类
			budgetCategories: [] // 预算分类列表
		};
	},
	onLoad() {
		// 从API获取预算数据
		this.fetchBudgetData();
	},
	methods: {
		// 获取预算数据
		fetchBudgetData() {
			this.isLoading = true;
			
			// 按年月查询预算
			getBudgetByYearMonth(this.currentYear, this.currentMonth)
				.then(res => {
					console.log('获取预算数据成功:', res.data);
					
					if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
						// 如果有预算数据
						this.hasBudgetData = true;
						const budget = res.data.data[0]; // 取第一条数据
						
						this.budgetId = budget.id;
						this.totalBudget = budget.amount || 0;
						this.dailyBudget = this.totalBudget / new Date(this.currentYear, this.currentMonth, 0).getDate(); // 计算每日预算
						
						// 获取预算分类数据
						this.fetchBudgetCategories();
					} else {
						// 如果没有预算数据
						this.hasBudgetData = false;
						this.budgetId = null;
						this.totalBudget = 0;
						this.totalExpense = 0;
						this.remainingBudget = 0;
						this.dailyBudget = 0; // 重置每日预算
						this.budgetCategories = [];
					}
				})
				.catch(err => {
					console.error('获取预算数据失败:', err);
					this.hasBudgetData = false;
					this.budgetId = null;
					this.totalBudget = 0;
					this.totalExpense = 0;
					this.remainingBudget = 0;
					this.dailyBudget = 0; // 重置每日预算
					this.budgetCategories = [];
					
					uni.showToast({
						title: '获取预算数据失败',
						icon: 'none'
					});
				})
				.finally(() => {
					this.isLoading = false;
				});
		},
		
		// 获取环形图渐变样式
		getProgressGradient() {
			// 计算使用百分比
			const usedPercent = this.totalBudget > 0 ? Math.min((this.totalExpense / this.totalBudget) * 100, 100) : 0;
			const degree = (usedPercent / 100) * 360;
			
			// 根据剩余预算选择颜色
			let color = '#4CD964'; // 绿色，默认充足
			
			if (this.remainingBudget <= 100) {
				color = '#FF3B30'; // 红色，严重不足
			} else if (this.remainingBudget <= 500) {
				color = '#FF9500'; // 橙色，预算不足
			}
			
			// 创建圆环渐变
			return `conic-gradient(
				${color} 0deg ${degree}deg,
				#EEEEEE ${degree}deg 360deg
			)`;
		},
		
		// 获取已使用预算百分比
		getUsedPercentage() {
			if (this.totalBudget <= 0) return 0;
			const percentage = Math.min((this.totalExpense / this.totalBudget) * 100, 100);
			return Math.round(percentage); // 四舍五入到整数
		},
		
		// 跳转到编辑预算页面
		navigateToEditBudget() {
			// 构建预算数据
			const budgetData = {
				id: this.budgetId,
				totalBudget: this.totalBudget,
				year: this.currentYear,
				month: this.currentMonth
			};
			
			// 编码为URL参数
			const budgetDataParam = encodeURIComponent(JSON.stringify(budgetData));
			
			// 跳转到编辑页面
			uni.navigateTo({
				url: `/pages/budget/budget-edit?budgetData=${budgetDataParam}`
			});
		},
		
		// 计算分类预算进度百分比
		calculateCategoryProgress(category) {
			if (!category) return 0;
			// 优先使用API返回的usagePercentage
			if (category.usagePercentage !== undefined) {
				return Math.min(category.usagePercentage, 100);
			}
			// 如果没有usagePercentage，则使用spent和amount计算
			if (category.amount <= 0) return 0;
			return Math.min((category.spent / category.amount) * 100, 100);
		},
		
		// 获取分类预算进度条颜色
		getCategoryProgressColor(category) {
			const remaining = category.amount - category.spent;
			
			if (remaining < 0) {
				return '#F44336'; // 红色，超预算
			} else if (remaining <= category.amount * 0.2) {
				return '#FF9800'; // 橙色，预算即将用完
			} else {
				return '#4CAF50'; // 绿色，预算充足
			}
		},
		
		// 编辑分类预算
		editCategory(category) {
			// 将分类数据编码为URL参数
			const categoryData = encodeURIComponent(JSON.stringify({
				...category,
				year: this.currentYear,
				month: this.currentMonth
			}));
			
			uni.navigateTo({
				url: `/pages/budget/budget-category-edit?categoryData=${categoryData}`
			});
		},
		
		// 跳转到添加分类页面
		navigateToAddCategory() {
			if (this.hasBudgetData) {
				// 已有预算，添加分类
				const params = encodeURIComponent(JSON.stringify({
					year: this.currentYear,
					month: this.currentMonth,
					budgetId: this.budgetId
				}));
				
				uni.navigateTo({
					url: `/pages/budget/budget-category-edit?params=${params}`
				});
			} else {
				// 无预算，创建预算
				const params = encodeURIComponent(JSON.stringify({
					year: this.currentYear,
					month: this.currentMonth
				}));
				
				uni.navigateTo({
					url: `/pages/budget/budget-edit?params=${params}`
				});
			}
		},
		
		// 显示日期选择器
		showDatePicker() {
			this.$refs.datePopup.open();
		},
		
		// 日期选择确认
		confirmDatePicker() {
			this.$refs.datePopup.close();
			this.currentYear = this.tempYear;
			this.currentMonth = this.tempMonth;
			// 重新加载预算数据
			this.fetchBudgetData();
		},
		
		// 日期选择取消
		cancelDatePicker() {
			this.$refs.datePopup.close();
		},
		
		// 日期选择器变化
		onDatePickerChange(e) {
			const selectedYear = this.yearArray[e.detail.value[0]];
			const selectedMonth = this.monthArray[e.detail.value[1]];
			this.tempYear = selectedYear;
			this.tempMonth = selectedMonth;
		},
		
		// 获取预算分类数据
		fetchBudgetCategories() {
			this.isLoading = true;
			
			if (!this.budgetId) {
				this.isLoading = false;
				this.budgetCategories = [];
				return;
			}
			
			getBudgetCategoryList(this.budgetId)
				.then(res => {
					console.log('获取预算分类数据成功:', res.data);
					
					if (res.data.code === 200 && res.data.data) {
						// 新的API返回格式
						const recordData = res.data.data.records && res.data.data.records.length > 0 
							? res.data.data.records[0] 
							: null;
						
						if (recordData) {
							// 更新总预算、总支出和剩余预算
							this.totalBudget = recordData.totalBudget || 0;
							this.totalExpense = recordData.totalMonthlyExpense || 0;
							this.remainingBudget = recordData.remainingBudget || 0;
							
							// 计算每日剩余预算
							this.calculateDailyBudget();
							
							// 更新预算分类列表
							this.budgetCategories = (recordData.categories || []).map(item => {
								return {
									id: item.budgetCategory.id,
									budgetId: item.budgetCategory.budgetId,
									categoryId: item.budgetCategory.categoryId,
									name: item.category ? item.category.name : '未分类',
									amount: item.budgetCategory.amount || 0,
									spent: item.monthlyExpense || 0,
									color: item.category ? item.category.color : '#4CAF50',
									iconType: item.category ? item.category.icon : 'wallet',
									icon: item.category ? item.category.icon : '',
									usagePercentage: item.usagePercentage || 0
								};
							});
						} else {
							this.budgetCategories = [];
							// 如果没有记录，重置总预算、总支出和剩余预算
							this.totalBudget = 0;
							this.totalExpense = 0;
							this.remainingBudget = 0;
							this.dailyBudget = 0;
						}
					} else {
						this.budgetCategories = [];
						uni.showToast({
							title: res.data.msg || '获取预算分类数据失败',
							icon: 'none'
						});
					}
				})
				.catch(err => {
					console.error('获取预算分类数据失败:', err);
					this.budgetCategories = [];
					uni.showToast({
						title: '获取预算分类数据失败',
						icon: 'none'
					});
				})
				.finally(() => {
					this.isLoading = false;
				});
		},
		
		// 计算每日剩余预算
		calculateDailyBudget() {
			// 获取当前日期
			const today = new Date();
			const currentYear = this.currentYear;
			const currentMonth = this.currentMonth;
			
			// 如果是当前月份，计算从今天到月底的天数
			if (currentYear === today.getFullYear() && currentMonth === today.getMonth() + 1) {
				// 当前月份的最后一天
				const lastDay = new Date(currentYear, currentMonth, 0).getDate();
				// 当前是几号
				const currentDay = today.getDate();
				// 剩余天数（包括今天）
				const remainingDays = lastDay - currentDay + 1;
				
				// 计算每日预算
				this.dailyBudget = remainingDays > 0 ? this.remainingBudget / remainingDays : 0;
				console.log(`本月剩余${remainingDays}天，每日预算${this.dailyBudget.toFixed(2)}`);
			} else {
				// 如果不是当前月份，则按整月计算
				const daysInMonth = new Date(currentYear, currentMonth, 0).getDate();
				this.dailyBudget = daysInMonth > 0 ? this.remainingBudget / daysInMonth : 0;
				console.log(`${currentYear}年${currentMonth}月共${daysInMonth}天，每日预算${this.dailyBudget.toFixed(2)}`);
			}
		}
	}
}
</script>

<style lang="scss">

.budget-container {
	background-color: $background-color;
	display: flex;
	flex-direction: column;
	position: relative;
	padding-bottom: 120rpx; // 为底部按钮预留空间
	height: 100%;
	box-sizing: border-box; // 确保padding不增加总高度
	
	// 月份选择器
	.month-selector {
		height: 90rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: $primary-color;
		padding: 0 40rpx;
		flex-shrink: 0; // 防止压缩
		
		.month-selector-left {
			display: flex;
			align-items: center;
			
			text {
				font-size: 32rpx;
				font-weight: bold;
				color: $text-color;
				margin-right: 10rpx;
			}
		}
		
		.month-selector-right {
			.edit-btn {
				padding: 10rpx 30rpx;
				background-color: rgba(255, 255, 255, 0.3);
				border-radius: 30rpx;
				
				text {
					color: $text-color;
					font-size: 28rpx;
				}
			}
			
			.placeholder-btn {
				width: 90rpx; // 与编辑按钮宽度相近
				height: 50rpx; // 与编辑按钮高度相近
			}
		}
	}
	
	// 预算概览
	.budget-overview {
		background-color: #fff;
		padding: 40rpx;
		display: flex;
		margin-bottom: 20rpx;
		flex-shrink: 0; // 防止压缩
		
		// 左侧环形图
		.chart-container {
			flex: 1.2;
			display: flex;
			justify-content: center;
			align-items: center;
			
			.chart-circle {
				width: 200rpx; // 减小环形图尺寸
				height: 200rpx;
				position: relative;
				display: flex;
				justify-content: center;
				align-items: center;
				
				.progress-ring {
					position: absolute;
					width: 100%;
					height: 100%;
					border-radius: 50%;
					transform: rotate(-90deg); // 从顶部开始
				}
				
				.inner-circle {
					width: 140rpx; // 减小内圆尺寸
					height: 140rpx;
					border-radius: 50%;
					background-color: #fff;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					z-index: 1;
					box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.05);
					
					.remaining-amount {
						font-size: 38rpx;
						font-weight: bold;
						color: $text-color;
					}
					
					.remaining-text {
						font-size: 20rpx;
						color: $text-color-lighter;
						margin-top: 6rpx;
					}
				}
			}
		}
		
		// 右侧预算信息
		.budget-info {
			flex: 1.2; // 增加宽度比例
			padding-left: 20rpx;
			
			.budget-row {
				display: flex;
				align-items: center;
				margin-bottom: 15rpx;
				
				.budget-label {
					width: 160rpx;
					font-size: 28rpx;
					color: $text-color-lighter;
				}
				
				.budget-value {
					font-size: 32rpx;
					font-weight: bold;
					color: $text-color;
					flex: 1;
					
					&.expense-value {
						color: #F44336; // 支出显示红色
					}
				}
				
				&.daily-budget {
					// margin-top: 10rpx;
					padding-top: 10rpx;
					border-top: 1px dashed #e0e0e0;
					
					.budget-value {
						color: #4CAF50; // 每日预算显示绿色
					}
				}
			}
		}
	}
	
	// 预算分类列表
	.budget-categories {
		background-color: #fff;
		flex: 1; // 占用剩余空间
		height: 0; // 让flex: 1生效
		overflow-y: auto; // 只有这里允许垂直滚动
		
		.category-item {
			display: flex;
			justify-content: space-between;
			padding: 30rpx 40rpx;
			border-bottom: 1px solid $border-color;
			
			.category-left {
				display: flex;
				flex: 1;
				
				.category-icon {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-right: 20rpx;
					
					.category-icon-image {
						width: 50rpx;
						height: 50rpx;
					}
				}
				
				.category-info {
					flex: 1;
					
					.category-name {
						font-size: 30rpx;
						color: $text-color;
						margin-bottom: 15rpx;
					}
					
					.category-progress {
						width: 100%;
						
						progress {
							margin-bottom: 10rpx;
						}
						
						.progress-info {
							display: flex;
							justify-content: space-between;
							
							text {
								font-size: 24rpx;
								color: $text-color-lighter;
							}
						}
					}
				}
			}
			
			.category-right {
				display: flex;
				align-items: center;
				margin-left: 20rpx;
				
				.remaining-budget {
					font-size: 32rpx;
					font-weight: bold;
					color: $text-color;
					
					&.over-budget {
						color: #F44336; // 超预算显示红色
					}
				}
			}
		}
		
		.no-data {
			padding: 100rpx 0;
			text-align: center;
			color: $text-color-lighter;
		}
	}
	
	// 无预算数据时的样式
	.empty-budget {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #fff;
		
		.empty-image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 30rpx;
		}
		
		.empty-text {
			font-size: 28rpx;
			color: $text-color-lighter;
		}
	}
	
	// 添加分类按钮
	.add-category-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: $primary-color;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 10; // 确保按钮在最上层
		
		text {
			font-size: 32rpx;
			color: $text-color;
			font-weight: bold;
		}
	}
}

// 加载状态样式
.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40rpx 0;
	flex: 1;
}

// 日期选择器弹窗样式
.date-picker-popup {
	background-color: #fff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
	overflow: hidden;
	
	.picker-header {
		display: flex;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1px solid $border-color;
		
		text {
			font-size: 32rpx;
			color: $text-color;
			
			&:last-child {
				color: $primary-color;
				font-weight: bold;
			}
		}
	}
	
	.picker-view {
		width: 100%;
		height: 500rpx;
		
		.picker-item {
			line-height: 80rpx;
			text-align: center;
			font-size: 32rpx;
		}
	}
}
</style> 